package com.action.ui.fragment;


import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.action.childbase.ChildBaseFragment;
import com.base.app_core.View.xrecyclerview.RecyclerAdapter;
import com.base.app_core.View.xrecyclerview.RecyclerViewHolder;
import com.base.app_core.model.Paginated;
import com.base.app_core.model.UserHistoryStock;
import com.base.app_core.service.pressenter.XYBUPressenter;
import com.base.app_core.service.user.model.User;
import com.base.app_core.util.AppConstants;
import com.xinglai.yun.R;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.qq.e.ads.banner.ADSize;
import com.qq.e.ads.banner.AbstractBannerADListener;
import com.qq.e.ads.banner.BannerView;

import java.util.Collection;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class StockCountLogFragment extends ChildBaseFragment<XYBUPressenter> {


    public StockCountLogFragment() {
        // Required empty public constructor
    }

    @Inject
    User user;

    @BindView(R.id.stock_count)
    TextView stockCount;

    @BindView(R.id.data_container)
    XRecyclerView dataContainer;

    @BindView(R.id.bannerContainer)
    FrameLayout adView;

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    public static class StockCountAdapter extends RecyclerAdapter<UserHistoryStock, StockCountAdapter.ViewHolder> {

        @Override
        protected void fillData(UserHistoryStock item, StockCountAdapter.ViewHolder holder) {
            holder.content.setText(item.getContent());
            Integer type = item.getType();
            if (type == null) {
                type = 0;
            }
            if (type == 1) {
                holder.changeAccount.setText("-" + item.getChangeStock());
                holder.changeAccount.setTextColor(holder.itemView.getResources().getColor(R.color.red));
            } else {
                holder.changeAccount.setText("+" + item.getChangeStock());
                holder.changeAccount.setTextColor(holder.itemView.getResources().getColor(R.color.green));
            }

            holder.changeDate.setText(item.getCreateAt());
            holder.currentPrice.setText("余:" + item.getCurrentStock());
        }

        @Override
        protected int getItemLayoutId() {
            return R.layout.unit_stock_price_log;
        }

        public class ViewHolder extends RecyclerViewHolder {
            @BindView(R.id.content)
            TextView content;
            @BindView(R.id.changeAccount)
            TextView changeAccount;
            @BindView(R.id.change_date)
            TextView changeDate;
            @BindView(R.id.current_price)
            TextView currentPrice;

            public ViewHolder(View itemView) {
                super(itemView);
            }

        }
    }

    private void requestGDTBanner() {
        BannerView bv = new BannerView(getActivity(), ADSize.BANNER, "1107815226", "8070337977963314");
        // 注意：如果开发者的banner不是始终展示在屏幕中的话，请关闭自动刷新，否则将导致曝光率过低。
        // 并且应该自行处理：当banner广告区域出现在屏幕后，再手动loadAD。
        bv.setRefresh(30);
        bv.setADListener(new AbstractBannerADListener() {

            @Override
            public void onNoAD(com.qq.e.comm.util.AdError error) {
                Log.i(
                        "AD_DEMO",
                        String.format("Banner onNoAD，eCode = %d, eMsg = %s", error.getErrorCode(),
                                error.getErrorMsg()));
            }

            @Override
            public void onADReceiv() {
                Log.i("AD_DEMO", "ONBannerReceive");
            }
        });
        adView.addView(bv);
        bv.loadAD();
    }


    @Override
    protected void initView() {
        super.initView();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        dataContainer.setLayoutManager(layoutManager);
        dataContainer.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        stockCountAdapter = new StockCountAdapter();
        dataContainer.setAdapter(stockCountAdapter);
        dataContainer.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                if (dataContainer == null) {
                    return;
                }
                pageNo = 1;
                if (null != mPresenter)
                    mPresenter.fetchStockCountLog(pageNo);
                dataContainer.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (null != dataContainer)
                            dataContainer.refreshComplete();
                    }
                }, AppConstants.Const.REFRESHTIME);
            }

            @Override
            public void onLoadMore() {
                pageNo++;
                if (null != mPresenter)
                    mPresenter.fetchStockCountLog(pageNo);
                if (dataContainer == null) {
                    return;
                }
                dataContainer.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (dataContainer == null) {
                            return;
                        }

                        dataContainer.loadMoreComplete();
                    }
                }, AppConstants.Const.REFRESHTIME);
            }
        });
        dataContainer.setEmptyView(getEmptyView(dataContainer, "当前没有记录", "", null));
        requestGDTBanner();
    }

    int pageNo = 1;
    private StockCountAdapter stockCountAdapter;

    @Override
    protected boolean isNeedShowLoading() {
        return true;
    }

    @Override
    protected boolean needShowError() {
        return true;
    }

    @Override
    protected void loadData() {
        super.loadData();
        if (null != mPresenter)
            mPresenter.fetchStockCountLog(pageNo);
    }

    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        if (object instanceof Collection) {
            if (tClass == UserHistoryStock.class) {
                if (stockCountAdapter == null || dataContainer == null) {
                    return;
                }

                List<UserHistoryStock> o = (List<UserHistoryStock>) object;
                if (pageNo == 1) {
                    stockCountAdapter.clear();
                    if (!o.isEmpty()) {
                        UserHistoryStock userHistoryStock = o.get(0);
                        stockCount.setText(userHistoryStock.getCurrentStock());
                    } else {
                        stockCount.setText("0");
                    }
                }
                stockCountAdapter.addAll(o);

                stockCountAdapter.notifyDataSetChanged();
                dataContainer.setLoadingMoreEnabled(paginated.getHasMore());

            }
        }
        setState(AppConstants.STATE_SUCCESS);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_stock_count_log;
    }

}
